<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="项目标段" prop="institutionCode">
        <el-select
          v-model="queryParams.institutionCode"
          placeholder="请选择"
          size="small"
          style="width: 240px" @change="handleBidChange"
        >
          <el-option-group
            v-for="group in projectBidOptions"
            :key="group.name"
            :label="group.name">
            <el-option
              v-for="item in group.bids"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-form-item label="开始日期" prop="beginDate">
        <el-date-picker size="small"
                        type="date"
                        v-model="beginDate"
                        :disabled="true"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="截止日期" prop="endDate">
        <el-date-picker size="small"
                        type="date"
                        v-model="endDate"
                        :disabled="true"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="上报日期" prop="businessReportingDate">
        <el-input v-model="businessReportingDate" :disabled="true" />
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleGen"
          :loading="genLoading"
          v-hasPermi="['agency:period:gen']"
        >生成</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['agency:period:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['agency:period:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['agency:period:remove']"
        >删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="periodList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="期次" align="center" prop="periodName" />
      <el-table-column label="开始日期" align="center" prop="beginDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年" align="center" prop="year" />
      <el-table-column label="月" align="center" prop="month" />
      <el-table-column label="清单模板" align="center" prop="templateName" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工期对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="期　　次" prop="periodName">
          <el-input v-model="form.periodName" placeholder="请输入期次" :disabled="true" />
        </el-form-item>
        <el-form-item label="开始日期" prop="beginDate">
          <el-date-picker size="small"
            v-model="form.beginDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期" style="width: 100%" :disabled="true">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="截止日期" prop="endDate">
          <el-date-picker size="small"
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期" style="width: 100%"
            :picker-options="endDatePickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="清单模板" prop="templateCode">
          <el-select v-model="form.templateCode" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in templateOptions"
              :key="item.templateCode"
              :label="item.templateName"
              :value="item.templateCode">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listPeriod, getPeriod, delPeriod, addPeriod, updatePeriod, getInstitutionDetail, genPeriod } from "@/api/agency/period";
import { selectProjectAgencyBid } from "@/api/project/bid";

export default {
  name: "Period",
  data() {
    return {
      // 项目标段分组下拉框
      projectBidOptions: [],
      // 开始日期
      beginDate: null,
      // 截止日期
      endDate: null,
      // 业务上报日
      businessReportingDate: '',
      // 遮罩层
      loading: false,
      // 生成遮罩层
      genLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工期表格数据
      periodList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        institutionCode: null,
      },
      // 表单参数
      form: {},
      // 模板下拉框
      templateOptions: [],
      endDatePickerOptions: {
        disabledDate: (time) => {
          if (this.form.beginDate) {
            return new Date(this.form.beginDate).getTime() > time.getTime();
          }
        }
      },
      // 表单校验
      rules: {
        endDate: [
          { required: true, message: "截止日期不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.initBidSelect();
  },
  methods: {
    /** 初始化标段下拉框 */
    initBidSelect() {
      selectProjectAgencyBid().then(response => {
        this.projectBidOptions = response.data;
        if (this.projectBidOptions.length > 0) {
          this.queryParams.institutionCode = this.projectBidOptions[0].bids[0].code;
          // 查询机构开始日期和截止日期，业务上报日
          this.getInstitutionDetail();
          this.getList();
        }
      });
    },
    // 查询标段开始日期，截止日期，业务上报日
    getInstitutionDetail() {
      getInstitutionDetail({ institutionCode: this.queryParams.institutionCode}).then(response => {
        this.beginDate = response.beginDate;
        this.endDate = response.endDate;
        this.businessReportingDate = response.businessReportingDate;
      });
    },
    /** 查询工期列表 */
    getList() {
      this.loading = true;
      listPeriod(this.queryParams).then(response => {
        this.periodList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        periodId: null,
        periodName: null,
        institutionCode: null,
        beginDate: null,
        endDate: null,
        year: null,
        month: null,
        isLock: null,
        isMeterage: null,
        currentMeterage: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.periodId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 标段下拉框发生变化
    handleBidChange() {
      this.queryParams.pageNum = 1;
      this.getInstitutionDetail();
      this.getList();
    },
    /** 生成按钮操作 */
    handleGen() {
      if (this.beginDate == null) {
        this.$modal.msgError("请先设置标段开始日期");
        return;
      }
      if (this.endDate == null) {
        this.$modal.msgError("请先设置标段截止日期");
        return;
      }
      this.$modal.confirm('生成工期将会删除原有工期，确定生成？').then(() => {
        this.genLoading = true;
        return genPeriod({ institutionCode: this.queryParams.institutionCode});
      }).then(() => {
        this.genLoading = false;
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
        this.genLoading = false;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.beginDate == null) {
        this.$modal.msgError("请先设置标段开始日期");
        return;
      }
      if (this.endDate == null) {
        this.$modal.msgError("请先设置标段截止日期");
        return;
      }
      addPeriod({ institutionCode: this.queryParams.institutionCode}).then(response => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const periodId = row.periodId || this.ids
      getPeriod(periodId).then(response => {
        this.form = response.period;
        this.templateOptions = response.templates;
        this.open = true;
        this.title = "修改工期";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.periodId != null) {
            updatePeriod(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPeriod(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('确定删除最后一期工期数据吗？').then(() => {
        return delPeriod({ institutionCode: this.queryParams.institutionCode});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
      });
    }
  }
};
</script>
